package com.nextive.weightlogger.ui;

import java.lang.reflect.Constructor;

import android.content.Context;
import android.widget.LinearLayout;

/**
 * Wraps the NumberPicker class which is not publicly accessible.
 * 
 * It exposes most used methods of NumberPicker, internally invoked through
 * reflection.
 * 
 * @author Federico Baseggio <fedebaseggio@gmail.com>
 */
public class NumberPickerWrapper extends LinearLayout {
	private LinearLayout numberPicker;

	/**
	 * Creates an instance that wraps a NumberPicker instance so its methods out
	 * of scope can be invoked.
	 * 
	 * @param context
	 * @param numberPicker The number picker to wrap.
	 */
	public NumberPickerWrapper(Context context, LinearLayout numberPicker) {
		super(context);
		this.numberPicker = numberPicker;
	}

	/**
	 * Creates a LinearLayout and adds a new NumberPicker instance to it.
	 * 
	 * @param context
	 */
	public NumberPickerWrapper(Context context) {
		super(context);
		Class<? extends LinearLayout> clss;
		try {
			clss = Class.forName("android.widget.NumberPicker").asSubclass(
					LinearLayout.class);
			Constructor<? extends LinearLayout> constructor = clss
					.getConstructor(Context.class);
			numberPicker = constructor.newInstance(context);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		this.addView(numberPicker);
	}
	
	/**
	 * Returns the wrapped NumberPicker instance.
	 * 
	 * @return The wrapped NumberPicker instance.
	 */
	public LinearLayout getNumberPicker()
	{
		return numberPicker;
	}

	/**
	 * Invokes setRange() on the wrapped NumberPicker instance.
	 * 
	 * @param minValue The minimum value to accept.
	 * @param maxValue The maximum value to accept.
	 */
	public void setRange(int minValue, int maxValue)
	{
		try {
			numberPicker.getClass().getMethod("setRange", int.class, int.class)
				.invoke(numberPicker, minValue, maxValue);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Invokes setCurrent() on the wrapped NumberPicker instance.
	 * 
	 * Sets the current value.
	 * 
	 * @param value The current value.
	 */
	public void setCurrent(int value)
	{
		try {
			numberPicker.getClass().getMethod("setCurrent", int.class)
				.invoke(numberPicker, value);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Invokes getCurrent() on the wrapped NumberPicker instance.
	 * 
	 * @return The current value.
	 */
	public int getCurrent()
	{
		try {
			return (Integer) numberPicker.getClass()
				.getMethod("getCurrent").invoke(numberPicker);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
